<template>
  <div id="group">
    <el-row class="bgColor">
      <el-col :xs="24" :sm="24" :lg="24" class="toFlex">
        <div class="item">
          <label for="cascader">选择项目:</label>
          <el-cascader
            placeholder="Yorkdale"
            :options="selector"
            filterable
            :show-all-levels="false"
            :collapse-tags="isMultiple ? true : false"
            v-model="selected"
            @change="toChange"
            clearable
            :props="{ multiple: isMultiple }"
            style="margin-left: 10px; width:12%"
            id="cascader"
            :class="{'mwidth': isMultiple}"
            >
          </el-cascader>

          <label v-if="isShow" for="weeks" style='margin:auto 15px;' :class='weekNum ? "weekDisplay1": "weekDisplay0"'>{{weekNum ? `第${weekNum}周` : "选择周: "}}</label>
          <el-date-picker
            id="weeks"
            style="margin: auto 0;"
            @change="changeWeek"
            v-if="isShow"
            v-model="weeks"
            format="yyyy年MM月dd日"
            :picker-options="{'firstDayOfWeek': 1}"
            placeholder="选择周">
          </el-date-picker>
<!--          <a-week-picker-->
<!--              placeholder="选择周"-->
<!--              v-model="weeks"-->
<!--              id="weeks"-->
<!--              v-if="isShow"-->
<!--              style="margin: auto 0;"-->
<!--              @change="changeWeek"-->
<!--              format='YYYY 第 w 周'-->
<!--          >-->
<!--            <a-icon slot="suffixIcon" type="calendar" />-->
<!--          </a-week-picker>-->

          <label v-if="isShow" for="levels" style="margin:auto 15px;">风险等级:</label>
          <el-select style="margin: auto 0;" @change="changeLevel" v-if="isShow" clearable multiple v-model="levels" placeholder="请选择风险等级">
            <el-option
              v-for="item in levelsOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>

          <label v-if="isShow" for="project_level" style="margin:auto 10px;">项目等级:</label>
          <el-select style="margin: auto 0;" @change="changeProjectLevel" v-if="isShow" clearable v-model="project_level" placeholder="请选择项目等级">

            <el-option
                v-for="item in projectLevel"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>

          <label v-if="isShow" for="deliver_center" style="margin:auto 10px;">主交付/产品中心:</label>
          <el-select style="margin: auto 0;" @change="changeInput" v-if="isShow" clearable v-model="deliver_center" multiple filterable collapse-tags placeholder="请选择主交付/产品中心">
            <el-row style="margin-left: 9%" >
              <el-col :lg='12' :xl='12' :xs='12'>
                <div ><el-button size='mini' @click='selectAllDelivery'>全选</el-button></div>
              </el-col>
              <el-col :lg='12' :xl='12' :xs='12'>
                <div><el-button size='mini' @click='toggleSelectAllDelivery'>反选</el-button></div>
              </el-col>
            </el-row>
            <el-option
                v-for="item in deliverCenterList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex';
import http from '@/views/sys/axios';
import Moment from 'moment';
Moment.locale('zh-cn')

export default {
    name: 'Group',
    props: {
      isMultiple: {
        type: Boolean,
        default: false
      },
      deliverCenterList: {
        type: Array,
        default: () => []
      },
      isShow: {
        type: Boolean,
        default: false
      }
    },
    computed: {
      ...mapState({
        dispose: state => state.conditions.dispose
      })
    },

    watch: {
      selected(newData){
          this.setGroupXzxm()
      }
    },
    created () {
      this.getOptionsResult()
    },
    data() {
      return {
        selector: [],
        selected: null,
        weeks: '',
        levels: [],
        weekNum: '',
        project_level: '',
        deliver_center: [],
        projectLevel: [
          {
            value: 'A类',
            label: 'A类'
          },
          {
            value: 'B类',
            label: 'B类'
          },
          {
            value: 'C类',
            label: 'C类'
          },
          {
            value: 'D类',
            label: 'D类'
          },
        ],
        levelsOptions: [
          {
            value: 3,
            label: '高风险'
          },
          {
            value: 2,
            label: '中风险'
          },
          {
            value: 1,
            label: '低风险'
          }
        ]
      }
    },
    methods: {

      ...mapMutations(['setGroupXzxm']),

      getTabledata(){
        const self = this
        http.get(`/api/data_summary/car/project/user/filter`)
        .then(res => {
          const { data,code } = res
          self.datas2 = res.condition
          if(code === 200){
             http.post(`/api/data_summary/car/project/data?page=${self.current}`, self.datas2)
             .then(res => {
              self.loading = true
              const { code, result, count } = res
              if(code === 200) {
                // console.log(222,res)
                self.prjStatus = self.datas2.project_status
                let list = result
                self.loading = false
                self.table = result
                self.tableInit = list
                self.total = count
                Object.keys(self.table).forEach(key => {
                  if(key === 'BU自评') {
                    self.isShowList.push({
                      isFolder: 'extension',
                      keyVal: key,
                      isShow: false
                    })
                  } else {
                    self.isShowList.push({
                      isFolder: 'default',
                      keyVal: key,
                      isShow: false
                    })
                  }
                })
              }
            })
              }
            })
      },
      selectAllDelivery() {
        this.deliver_center = this.deliverCenterList.map(item => item.value)
        this.changeInput(null)
      },
      toggleSelectAllDelivery() {
        this.deliver_center = this.deliverCenterList.filter(item => !this.deliver_center.includes(item.value)).map(item => item.value)
        this.changeInput(null)
      },
      ...mapMutations('conditions', [
        'setDispose'
      ]),
      changeWeek(val) {
        let year, week, yearWeek
        if(val != null) {
          // year = new Date(val).getFullYear()
          // week = Moment(this.weeks).utcOffset(480).format("WW")
          week = Moment(val).week() + 1
          year = Moment(val).year()
          yearWeek = `${year}-${week}`
          this.weekNum = week
        } else {
          yearWeek = ''
          this.weekNum = ''
        }
        this.setDispose({
          weeks: yearWeek
        })
      },
      changeLevel(val) {
        this.setDispose({
          levels: this.levels
        })
      },
      changeProjectLevel(val) {
        this.setDispose({
          project_level: this.project_level
        })
      },
      changeInput(val) {
        this.setDispose({
          deliver_center: this.deliver_center
        })
      },
      async statusChange(val) {
        try {
          const { code, project_list } = await this.getOptions()
          if(code === 200) {
            this.selector = project_list
            let item2, item3, all = [], id
            const val1 = this.selector[0].value
            if(Array.isArray(project_list) && project_list.length) {
              project_list[0].children.forEach(list2 => {
                item2 = list2.value
                list2.children.forEach(list3 => {
                  item3 = list3.value
                  all.push([val1, item2, item3])
                })
              })
            }
            this.selected = all
            id = this.computeMultiple(project_list, this.selected)
            this.setDispose({
              optionsList: this.selected,
              projectIdList: id
            })
            // this.computeInit(project_list)
          }
        } catch(err) {
          throw err
        }
      },
      getOptions() {
        return http.get(`/api/data_summary/car/project/list`)
      },
      async getOptionsResult() {
        try {
          const { code, project_list } = await this.getOptions()
          if(code === 200) {
            this.selector = project_list
            if(this.isMultiple) { // 多选状态下的处理逻辑
              if(this.dispose.optionsList.length) {
                this.selected = this.dispose.optionsList
              } else {
                this.computeInit(project_list)
              }
            } else { // 单选状态下的处理逻辑
              if(this.dispose.options.length) {
                this.selected = this.dispose.options
              } else {
                this.computeInit(project_list)
              }
            }
            let val = JSON.parse(localStorage.getItem('tmpval'))
            let valueList = JSON.parse(localStorage.getItem('tmpvalueList'))
            this.selected = val
          }
        } catch (err) {
          throw new Error(err)
        }

      },
      computeInit(project_list) {
        // const val1 = this.selector[0].value
        const val2 = this.selector[0].children[0].value
        const val3 = this.selector[0].children[0].children[0].value
        let item2, item3, all = []
        const val1 = this.selector[0].value
        if(Array.isArray(project_list) && project_list.length) {
          project_list[0].children.forEach(list2 => {
            item2 = list2.value
            list2.children.forEach(list3 => {
              item3 = list3.value
              all.push([val1, item2, item3])
            })
          })
        }

        let id = null
        if(this.isMultiple) {
          // 获取首次进入的ID 全选
          this.selected = all //[[val1, val2, val3]]

          id = this.computeMultiple(project_list, this.selected)
          this.setDispose({
            optionsList: this.selected,
            oriProjectIDList: all,
            projectIdList: id
          })
        } else {
          // 获取首次进入的ID
          this.selected = [val1, val2, val3]
          id = this.computeCondition(project_list, this.selected)
          this.setDispose({
            options: this.selected,
            projectId: id
          })
        }
      },
      computeCondition(list, filter) {
        if(Array.isArray(list) && !list.length) {
          return []
        }
        const outer = list.filter(item => item.value === filter[0]) // 事业群
        let mider = [] // 事业部
        let inner = [] // 项目

        if(outer[outer.length - 1].children) {
          let miderList = outer[outer.length - 1].children
          mider = miderList.filter(item => item.value === filter[1])

          if(mider[mider.length - 1].children) {
            let innerList = mider[mider.length - 1].children
            inner = innerList.filter(item => item.value === filter[2])
          }
        }
        const { value } = inner[0]
        return value
      },
      computeMultiple(list, filter) {
        if(Array.isArray(list) && !list.length) {
          return []
        }
        let multipleArr = []
        filter.forEach(item => {
          multipleArr.push(this.computeCondition(list, item))
        })
        return multipleArr
      },
      toChange(val) {
        let arr = this.selector
        if(this.isMultiple) {
          let valueList = this.computeMultiple(arr, val)

          localStorage.setItem('tmpval', JSON.stringify(val))
          localStorage.setItem('tmpvalueList', JSON.stringify(valueList))

          this.setDispose({
            optionsList: val,
            projectIdList: valueList
          })
        } else {
          let value = this.computeCondition(arr, val)
          this.$emit('getson', val[2])
          // console.log('我向父组件发射了一个事件', val[2]);

          this.setDispose({
            options: val,
            projectId: value
          })

        }
      }
    },
  }
</script>

<style lang="scss" scoped>

  #group{
    .bgColor{
      background: #ffffff;
      padding: 20px;
      .toFlex{
        display: flex;
        .item{
          display: flex;
          flex: 1;
          label{
            margin: auto 0;
          }
          #cascader, #selectd{
            margin: auto 0;
            width: 20%;
            &.mwidth{
              width: 23%;
            }
          }
          .item2{
            margin-left: 20px;
          }
        }
      }
    }

  }
  @media screen and (max-width: 1440px){
    #group .bgColor .toFlex .item #cascader.mwidth{
      width: 25%;
    }
  }
  /deep/.el-input--small .el-input__inner {
    line-height: 36px;
    height: 36px;
  }
  .formItem {
    padding-top: 2vh;
  }
  .weekDisplay0 {
  }
  .weekDisplay1 {
    color: red;
  }
</style>
